package cn.hqm.hqmtechnology.filters.interceptor;

import cn.hqm.hqmtechnology.annotations.PassToken;
import cn.hqm.hqmtechnology.utils.RedisUtil;
import cn.hqm.hqmtechnology.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;

@Component
@Slf4j
public class TokenFilterInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 在请求之前进行处理
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }

        // 过滤该请求是否带有Token,
        String authorization = request.getHeader("Authorization");
        if (Objects.isNull(authorization) || authorization.isEmpty() || authorization.equals("null")) {
            // 检查访问的接口方法上是否有PassToken注解,如果有放行
            if (handler instanceof HandlerMethod) {
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                PassToken passToken = handlerMethod.getMethod().getAnnotation(PassToken.class);
                if (passToken != null) {
                    return setResponseCodeAndReturn(response,HttpServletResponse.SC_OK,true);  // 如果使用了@PassToken注解，则不进行登录验证，直接放行
                } else {
                    return setResponseCodeAndReturn(response,HttpServletResponse.SC_UNAUTHORIZED,false);
                }
            }
        }
        // 如果token 不为空走token认证逻辑
        Object forValue = redisUtil.getForValue(authorization == null ? "" : authorization);
        if (Objects.nonNull(forValue)) {
            Map<String, Object> info = (Map<String, Object>) forValue;
            // 将上述信息存入ThreadLocal
            ThreadLocalUtil.threadLocalMap.set(info);
            return true;
        } else {
            // 设置状态码为401 - 未授权
            return setResponseCodeAndReturn(response,HttpServletResponse.SC_UNAUTHORIZED,false);
        }
    }

    private boolean setResponseCodeAndReturn(HttpServletResponse response,Integer code,boolean result) {
        response.setStatus(code);
        return result;
    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        // 在处理器方法执行后、视图渲染前进行处理
//        System.out.println("After handling the request");
//    }
//
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        // 在整个请求处理完成后进行处理，包括视图渲染完成后
//        System.out.println("After completing the request");
//    }
}